// components/popup/index.js
import {
  addRewardApi,
  getUserInfoApi
} from '../../api/my.js'
const app = getApp()
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    show: {
      type: Boolean,
      default: false
    },
    // 帖子id
    topicId: {
      type: String,
      default: ''
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    // 价格列表
    priceList: [8, 16, 32],
    // 选中价格
    price: '',
    scoin: 0
  },
  lifetimes: {
    attached() {
      if (!app.userId) return
      if (app.userInfo) {
        this.setData({
          scoin: +app.userInfo.scoin
        })
      } else {
        this.getUserProfile()
      }
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    // 获取用户数据，将善币进行更新
    async getUserProfile() {
      // 调用接口获取昵称和头像
      const res = await getUserInfoApi(app.userId)
      // 存储数据
      app.userInfo = res
      const {
        scoin
      } = res
      // 渲染数据
      this.setData({
        scoin
      })
    },
    // 点击取消
    onClose() {
      this.setData({
        show: false
      })
    },
    // 点击确定
    onCharge() {
      wx.redirectTo({
        url: '/pkgUser/pages/charge/index',
      })
      this.setData({
        show: false
      })
    },
    // 选择金额
    changePrice(e) {
      this.setData({
        price: +e.mark.price
      })
    },
    // 输入其他金额
    changePriceMore(e) {
      this.setData({
        price: +e.detail.value
      })
    },
    // 打赏
    async onReward() {
      const {
        price,
        topicId
      } = this.data
      if (price * 1 !== price) return wx.utils.toast('请选择爱心')
      if (price > app.userInfo.scoin) return this.triggerEvent('creditLow')
      try {
        await addRewardApi({
          rewardSCoin: price,
          topicId: topicId,
          userId: app.userId
        })
        this.setData({
          scoin: this.data.scoin - price
        })
        this.triggerEvent('rewardResult', {
          flag: true,
          price: price
        })
      } catch (err) {
        this.setData({
          show: false
        })
        this.triggerEvent('rewardResult', {
          flag: false
        })
      }

    }
  }
})